package com.bzkj.basicinfo.service.impl;

import com.bzkj.basicinfo.domain.CustomerMapping;
import com.bzkj.basicinfo.mapper.CustomerMappingMapper;
import com.bzkj.basicinfo.service.CustomerMappingService;
import com.bzkj.common.annotation.DataSource;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.enums.DataSourceType;
import com.bzkj.common.utils.DateUtils;
import com.bzkj.common.utils.SecurityUtils;
import com.bzkj.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 往来单位映射关系服务实现类
 * 
 * @author system
 * @date 2025-01-29
 */
@Service
public class CustomerMappingServiceImpl implements CustomerMappingService {
    
    @Autowired
    private CustomerMappingMapper customerMappingMapper;

    /**
     * 查询往来单位映射关系
     *
     * @param id 往来单位映射关系主键
     * @return 往来单位映射关系
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public CustomerMapping selectCustomerMappingById(Long id) {
        return customerMappingMapper.selectCustomerMappingById(id);
    }

    /**
     * 查询往来单位映射关系列表
     *
     * @param customerMapping 往来单位映射关系
     * @return 往来单位映射关系
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public List<CustomerMapping> selectCustomerMappingList(CustomerMapping customerMapping) {
        return customerMappingMapper.selectCustomerMappingList(customerMapping);
    }

    /**
     * 新增往来单位映射关系
     *
     * @param customerMapping 往来单位映射关系
     * @return 结果
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public AjaxResult insertCustomerMapping(CustomerMapping customerMapping) {
        // 检查映射关系是否已存在（支持一对多关系）
        CustomerMapping existing = customerMappingMapper.checkMappingExists(
            customerMapping.getMsfxCustomerId(), customerMapping.getErpCustomerCode());
        if (existing != null) {
            return AjaxResult.error("该码上放心客户与ERP客户的映射关系已存在");
        }

        customerMapping.setCreateBy(SecurityUtils.getUsername());
        customerMapping.setCreateTime(DateUtils.getNowDate());
        customerMapping.setUpdateTime(DateUtils.getNowDate());
        customerMapping.setDelFlag(0);

        if (customerMapping.getStatus() == null) {
            customerMapping.setStatus(1);
        }
        if (customerMapping.getMappingType() == null) {
            customerMapping.setMappingType(1); // 默认手动映射
        }
        if (customerMapping.getAuditStatus() == null) {
            customerMapping.setAuditStatus(0); // 默认待审核
        }

        int result = customerMappingMapper.insertCustomerMapping(customerMapping);
        return result > 0 ? AjaxResult.success("创建映射关系成功") : AjaxResult.error("创建映射关系失败");
    }

    /**
     * 修改往来单位映射关系
     *
     * @param customerMapping 往来单位映射关系
     * @return 结果
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public AjaxResult updateCustomerMapping(CustomerMapping customerMapping) {
        customerMapping.setUpdateBy(SecurityUtils.getUsername());
        customerMapping.setUpdateTime(DateUtils.getNowDate());

        int result = customerMappingMapper.updateCustomerMapping(customerMapping);
        return result > 0 ? AjaxResult.success("修改映射关系成功") : AjaxResult.error("修改映射关系失败");
    }

    /**
     * 批量删除往来单位映射关系
     *
     * @param ids 需要删除的往来单位映射关系主键
     * @return 结果
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public AjaxResult deleteCustomerMappingByIds(Long[] ids) {
        int result = customerMappingMapper.deleteCustomerMappingByIds(ids);
        return result > 0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    /**
     * 删除往来单位映射关系信息
     *
     * @param id 往来单位映射关系主键
     * @return 结果
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public AjaxResult deleteCustomerMappingById(Long id) {
        int result = customerMappingMapper.deleteCustomerMappingById(id);
        return result > 0 ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

    /**
     * 创建映射关系
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public AjaxResult createMapping(String msfxCustomerId, String msfxCustomerName, String msfxEntId,
                                  String erpCustomerCode, String erpCustomerName, String erpDanwbh, String remark) {

        if (StringUtils.isEmpty(msfxCustomerId) || StringUtils.isEmpty(erpCustomerCode)) {
            return AjaxResult.error("客户ID和编码不能为空");
        }

        // 检查映射关系是否已存在（支持一对多关系）
        CustomerMapping existing = customerMappingMapper.checkMappingExists(msfxCustomerId, erpCustomerCode);
        if (existing != null) {
            return AjaxResult.error("该码上放心客户与ERP客户的映射关系已存在");
        }

        CustomerMapping mapping = new CustomerMapping();
        mapping.setMsfxCustomerId(msfxCustomerId);
        mapping.setMsfxCustomerName(msfxCustomerName);
        mapping.setMsfxEntId(msfxEntId);
        mapping.setErpCustomerCode(erpCustomerCode);
        mapping.setErpCustomerName(erpCustomerName);
        mapping.setErpDanwbh(erpDanwbh);
        mapping.setRemark(remark);
        mapping.setStatus(1);
        mapping.setMappingType(1); // 手动映射
        mapping.setAuditStatus(1); // 自动审核通过（手动创建的映射关系）
        mapping.setAuditUser(SecurityUtils.getUsername());
        mapping.setAuditTime(DateUtils.getNowDate());
        mapping.setAuditRemark("手动创建映射关系，自动审核通过");
        mapping.setCreateBy(SecurityUtils.getUsername());
        mapping.setCreateTime(DateUtils.getNowDate());
        mapping.setUpdateTime(DateUtils.getNowDate());
        mapping.setDelFlag(0);

        int result = customerMappingMapper.insertCustomerMapping(mapping);
        return result > 0 ? AjaxResult.success("创建映射关系成功") : AjaxResult.error("创建映射关系失败");
    }

    /**
     * 批量创建映射关系（一个码上放心客户对应多个ERP客户）
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public AjaxResult createBatchMapping(String msfxCustomerId, String msfxCustomerName, String msfxEntId,
                                       String[] erpCustomerCodes, String[] erpCustomerNames, String[] erpDanwbhs, String remark) {

        if (StringUtils.isEmpty(msfxCustomerId) || erpCustomerCodes == null || erpCustomerCodes.length == 0) {
            return AjaxResult.error("码上放心客户ID和ERP客户编码不能为空");
        }

        if (erpCustomerCodes.length != erpCustomerNames.length || erpCustomerCodes.length != erpDanwbhs.length) {
            return AjaxResult.error("ERP客户信息数组长度不一致");
        }

        int successCount = 0;
        int failCount = 0;
        StringBuilder errorMessages = new StringBuilder();

        for (int i = 0; i < erpCustomerCodes.length; i++) {
            String erpCustomerCode = erpCustomerCodes[i];
            String erpCustomerName = erpCustomerNames[i];
            String erpDanwbh = erpDanwbhs[i];

            if (StringUtils.isEmpty(erpCustomerCode)) {
                failCount++;
                errorMessages.append("第").append(i + 1).append("个ERP客户编码为空; ");
                continue;
            }

            // 检查映射关系是否已存在
            CustomerMapping existing = customerMappingMapper.checkMappingExists(msfxCustomerId, erpCustomerCode);
            if (existing != null) {
                failCount++;
                errorMessages.append("与ERP客户[").append(erpCustomerName).append("]的映射关系已存在; ");
                continue;
            }

            CustomerMapping mapping = new CustomerMapping();
            mapping.setMsfxCustomerId(msfxCustomerId);
            mapping.setMsfxCustomerName(msfxCustomerName);
            mapping.setMsfxEntId(msfxEntId);
            mapping.setErpCustomerCode(erpCustomerCode);
            mapping.setErpCustomerName(erpCustomerName);
            mapping.setErpDanwbh(erpDanwbh);
            mapping.setRemark(remark);
            mapping.setStatus(1);
            mapping.setMappingType(1); // 手动映射
            mapping.setAuditStatus(1); // 自动审核通过（手动创建的映射关系）
            mapping.setAuditUser(SecurityUtils.getUsername());
            mapping.setAuditTime(DateUtils.getNowDate());
            mapping.setAuditRemark("批量创建映射关系，自动审核通过");
            mapping.setCreateBy(SecurityUtils.getUsername());
            mapping.setCreateTime(DateUtils.getNowDate());
            mapping.setUpdateTime(DateUtils.getNowDate());
            mapping.setDelFlag(0);

            int result = customerMappingMapper.insertCustomerMapping(mapping);
            if (result > 0) {
                successCount++;
            } else {
                failCount++;
                errorMessages.append("创建与ERP客户[").append(erpCustomerName).append("]的映射关系失败; ");
            }
        }

        String message = String.format("批量创建映射关系完成：成功%d个，失败%d个", successCount, failCount);
        if (failCount > 0) {
            message += "。失败原因：" + errorMessages.toString();
        }

        return successCount > 0 ? AjaxResult.success(message) : AjaxResult.error(message);
    }

    /**
     * 审核映射关系
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public AjaxResult auditMapping(Long id, Integer auditStatus, String auditRemark) {
        CustomerMapping mapping = customerMappingMapper.selectCustomerMappingById(id);
        if (mapping == null) {
            return AjaxResult.error("映射关系不存在");
        }

        mapping.setAuditStatus(auditStatus);
        mapping.setAuditUser(SecurityUtils.getUsername());
        mapping.setAuditTime(DateUtils.getNowDate());
        mapping.setAuditRemark(auditRemark);
        mapping.setUpdateBy(SecurityUtils.getUsername());
        mapping.setUpdateTime(DateUtils.getNowDate());

        int result = customerMappingMapper.updateCustomerMapping(mapping);
        return result > 0 ? AjaxResult.success("审核成功") : AjaxResult.error("审核失败");
    }

    /**
     * 获取已映射的码上放心客户ID列表
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public List<String> getMappedMsfxCustomerIds() {
        return customerMappingMapper.selectMappedMsfxCustomerIds();
    }

    /**
     * 获取已映射的ERP客户编码列表
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public List<String> getMappedErpCustomerCodes() {
        return customerMappingMapper.selectMappedErpCustomerCodes();
    }

    /**
     * 解除映射关系
     */
    @Override
    @DataSource(DataSourceType.MASTER)
    public AjaxResult removeMapping(Long mappingId) {
        try {
            // 查询映射关系是否存在
            CustomerMapping mapping = customerMappingMapper.selectCustomerMappingById(mappingId);
            if (mapping == null) {
                return AjaxResult.error("映射关系不存在");
            }

            // 删除映射关系
            int result = customerMappingMapper.deleteCustomerMappingById(mappingId);
            if (result > 0) {
                return AjaxResult.success("解除映射成功");
            } else {
                return AjaxResult.error("解除映射失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("解除映射失败：" + e.getMessage());
        }
    }
}
